﻿using Newtonsoft.Json;
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using Tyche.WebApiClient.TycheWebApiValidation;

namespace Tyche.WebApiClient.Http
{
    public class TycheHttpUtil
    {
        static TycheHttpUtil()
        {
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
        }

        /// <summary>
        /// Get
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="host"></param>
        /// <param name="service"></param>
        /// <param name="method"></param>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public static T Get<T>(string host, string service, string method, object parameter = null)
        {
            Valid(parameter);

            HttpWebResponse httpWebResponse = null;
            StreamReader streamReader = null;
            try
            {
                HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(
                    parameter == null
                    ? string.Format("{0}/{1}/{2}", host, service, method)
                    : string.Format("{0}/{1}/{2}?{3}", host, service, method, ConvertToURLParameter(parameter)));
                httpWebRequest.Method = "GET";
                httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                streamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.UTF8);
                var response = streamReader.ReadToEnd();
                return JsonConvert.DeserializeObject<T>(response);
            }
            finally
            {
                if (httpWebResponse != null)
                {
                    httpWebResponse.Close();
                }
                if (streamReader != null)
                {
                    streamReader.Close();
                }
            }
        }

        /// <summary>
        /// Post
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="host"></param>
        /// <param name="service"></param>
        /// <param name="method"></param>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public static T Post<T>(string host, string service, string method, object parameter = null)
        {
            Valid(parameter);

            HttpWebResponse httpWebResponse = null;
            StreamReader streamReader = null;
            Stream stream = null;
            try
            {
                var a = JsonConvert.SerializeObject(parameter);
                HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(
                    string.Format("{0}/{1}/{2}", host, service, method));
                httpWebRequest.Method = "POST";
                httpWebRequest.ContentType = "application/json";
                byte[] data = Encoding.UTF8.GetBytes(parameter == null ? "{}" : JsonConvert.SerializeObject(parameter));
                stream = httpWebRequest.GetRequestStream();
                stream.Write(data, 0, data.Length);
                stream.Close();
                httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                streamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.UTF8);
                return JsonConvert.DeserializeObject<T>(streamReader.ReadToEnd());
            }
            finally
            {
                if (httpWebResponse != null)
                {
                    httpWebResponse.Close();
                }
                if (streamReader != null)
                {
                    streamReader.Close();
                }
                if (stream != null)
                {
                    stream.Close();
                }
            }
        }

        /// <summary>
        /// 对象转换成url参数
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        private static string ConvertToURLParameter(object value)
        {
            return string.Join("&", value.GetType().GetProperties().Where(x => x.GetValue(value) != null).Select(x =>
            {
                if (x.PropertyType.IsEnum ||
                    (x.PropertyType.IsGenericType && x.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) && x.PropertyType.GetGenericArguments()[0].IsEnum))
                {
                    return x.Name + "=" + ((int)x.GetValue(value)).ToString();
                }
                else
                {
                    return x.Name + "=" + x.GetValue(value);
                }
            }));
        }

        /// <summary>
        /// CheckValidationResult
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="certificate"></param>
        /// <param name="chain"></param>
        /// <param name="errors"></param>
        /// <returns></returns>
        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true;
        }

        /// <summary>
        /// 验证参数
        /// </summary>
        /// <param name="parameter"></param>
        private static void Valid(object parameter)
        {
            if (parameter == null)
            {
                return;
            }

            foreach (var property in parameter.GetType().GetProperties())
            {
                var attribute = property.GetCustomAttributes(false).FirstOrDefault(a => a.GetType().GetInterfaces().Any(i => i == typeof(ITycheWebApiValidation)));

                if (attribute == null)
                {
                    continue;
                }

                ((ITycheWebApiValidation)attribute).TycheValid(property.GetValue(parameter));
            }
        }
    }
}
